<template>
  <div>
    <r-search
      :searchForm="searchForm"
      :searchHandle="searchHandle"
      :searchData="searchData"
    />

    <!-- <div>地图</div> -->
    <r-table
      :tableHandles="tableHandles"
      :isSelection="false"
      :isIndex="false"
      :isPagination="true"
      :tableData="tableData"
      :tableCols="tableCols"
      :tablePage="tablePage"
      :isHandle="true"
      @refresh="init()"
    ></r-table>

    <r-form
      labelWidth="150px"
      :isHandle="true"
      :formRules="formRules2"
      :formCols="formCols2"
      :formHandle="formHandle2"
      :formData="formData2"
      ref="elForm2"
      :inline="false"
      dialogWidth="850px"
    >
      <!-- 点击编辑按钮出现的模板，里面的站点地址 -->

      <div slot="slot3">
        <div
          id="searchResultPanel"
          style="
            border: 1px solid #c0c0c0;
            width: 150px;
            height: auto;
            display: none;
          "
        ></div>
        <p>
          点击地图确认坐标 经度：{{ formData2.lng }} 纬度：{{ formData2.lat }}
          <!-- *可以通过点击地图，快速找到站点地址 -->
        </p>
        <div id="l-map"></div>
      </div>
    </r-form>

    <warehouse_gate
      :res="warehouse_gate_data"
      v-if="warehouse_gate_data.show"
      v-on:warehouse_gate_dall="warehouse_gate_dall"
    ></warehouse_gate>

    <Abnormal_record ref="Abnormal_record"></Abnormal_record>

    <useDetailDialog
      :visible.sync="visible"
      :useDetail="useDetail"
    ></useDetailDialog>
  </div>
</template>
<script>
import warehouse_gate from "./cus/warehouse_gate";
import Abnormal_record from "./cus/Abnormal_record";
import baidumap from "../js/baidumap";
import useDetailDialog from "./cus/useDetailDialog.vue";
export default {
  components: {
    warehouse_gate,
    Abnormal_record,
    useDetailDialog
  },
  data() {
    const checkAge = (rule, value, callback) => {
      setTimeout(() => {
        if (isNaN(value)) {
          callback(new Error("请输入数字值"));
        } else {
          if (value < 0) {
            callback(new Error("不能小于0"));
          } else {
            callback();
          }
        }
      }, 200);
    };
    return {
      // checkboxGroup: "",
      pt: "116.331398, 39.897445",
      userType: "", //反映是代理商还是运营商
      visible: false,
      useDetail: {
        deviceType: "3",
        deviceNo: "",
        deviceStatus: "",
        totalMoney: 0,
        totalOrder: 0,
        serverTime: 0,
        engaged: []
      },

      baiduMap: null,
      warehouse_gate_data: {
        id: "",
        show: false
      },
      searchData: {
        deviceName: "",
        deviceNo: "",
        deviceStatus: "",
        operatorId: "",
        agentId: "",
        distStatus: "",
        commonType: "",
        deviceType: 3,
        siteId: ""
      },
      // 搜索栏信息
      searchForm: [
        {
          type: "input",
          prop: "deviceNo",
          placeholder: "设备编号"
          // width: 150
        },
        {
          type: "select",
          prop: "siteId",
          placeholder: "铺设站点",
          width: 150,
          options: []
        },
        {
          type: "input",
          prop: "deviceName",
          placeholder: "设备名称"
          // width: 150
        },
        {
          type: "select",
          prop: "operatorId",
          placeholder: "所属运营商",
          options: [],
          // width: 150,
          isShow: () => {
            return sessionStorage.role == "platform" ? true : false;
          }
        },
        {
          type: "select",
          prop: "agentId",
          placeholder: "所属代理商",
          options: [],
          // width: 150,
          isShow: () => {
            return sessionStorage.role == "operator" ? true : false;
          }
        },
        {
          type: "select",
          prop: "distStatus",
          placeholder: "是否分配",
          // width: 150,
          options: [
            { label: "未分发", value: "0" },
            { label: "已分发", value: "1" }
          ]
        },
        {
          type: "select",
          prop: "whetherPublic",
          placeholder: "设备类型",
          // width: 150,
          options: [
            { label: "内部设备", value: 0 },
            { label: "公开设备", value: 1 }
          ]
        },
        {
          type: "select",
          prop: "commonType",
          placeholder: "公有类型",
          // width: 150,
          options: [
            { label: "公有", value: "1" },
            { label: "私有", value: "2" }
          ]
        }
      ],
      // 搜索按钮
      searchHandle: [
        {
          label: "搜索",
          type: "success",
          icon: "el-icon-search",
          handle: e => this.init()
        }
      ],
      //  添加设备按钮
      tableHandles: [
        {
          label: "添加设备",
          type: "primary",
          handle: e => {
            this.formData2.id = null;
            this.formData2.lat = 22.977337;
            this.formData2.lng = 113.303703;
            if (sessionStorage.role == "operator") {
              this.formCols2[
                this.labIndex2(this.formCols2, "siteId")
              ].options = [];
            }

            this.elFormVisible("", "elForm2").then(res => {
              this.map();
            });
          }
        }
      ],
      tableData: [],
      //表格信息
      tableCols: [
        {
          label: "设备编号",
          prop: "deviceNo"
        },
        {
          label: "二维码",
          type: "image",
          width: 100,
          prop: "qrCode"
        },
        {
          label: "设备名称",
          prop: "deviceName"
        },
        {
          label: "铺设站点",
          prop: "name"
        },
        {
          label: "当前定位",
          prop: "address"
        },
        {
          label: "充电柜套餐",
          prop: "mealName",
          width: 100,

          isShow: e => this.userType == "代理商"
        },
        {
          label: "设备类型",
          prop: "whetherPublic",
          formatter: e => {
            if (e.whetherPublic == 0) {
              return "内部设备";
            } else if (e.whetherPublic == 1) {
              return "公开设备";
            } else {
              return "-";
            }
          }
        },
        // {
        //   label: "所属代理商",
        //   prop: "agentName",
        //   width: 100,
        //   isShow: e => sessionStorage.role == "operator"
        // },

        {
          label: "运维人员",
          prop: "merName"
        },
        {
          label: "广告合集",
          prop: "advertList"
        },
        {
          label: "电量表",
          prop: "usedElectric"
        },
        {
          label: "设备状态",
          prop: "deviceStatus",
          formatter: e => {
            if (e.deviceStatus == 1) {
              return "(在线)运行中";
            } else if (e.deviceStatus == 2) {
              return "离线";
            } else if (e.deviceStatus == 3) {
              return "设备故障";
            } else if (e.deviceStatus == 0) {
              return "-";
            }
          }
        },
        {
          label: "更新时间",
          prop: "lastTime"
        },
        {
          label: "启用状态",
          type: "switch",
          prop: "useStatus",
          values: [1, 2],
          change: row => this.changestate(row)
        },
        {
          label: "操作",
          type: "button",
          width: 250,
          btnList: [
            {
              label: "使用详情",
              type: "text",
              handle: async row => {
                this.useDetail.deviceNo = row.deviceNo;
                this.useDetail.deviceStatus = row.deviceStatus;
                const res = await this.apis.cabinet_detailList(row.id, "3");
                const data = res.data.extend;
                this.useDetail.serverTime = data.serverTime;
                this.useDetail.totalMoney = data.totalMoney;
                this.useDetail.totalOrder = data.totalOrder;
                this.useDetail.engaged = data.engaged;
                this.visible = true;
              }
            },
            {
              label: "查看仓门",
              type: "text",
              handle: row => {
                this.warehouse_gate_data.id = row.id;
                this.warehouse_gate_data.show = true;
              }
            },
            {
              label: "异常记录",
              type: "text",
              handle: row => {
                this.$refs.Abnormal_record.show_fun(row);
              }
            },
            {
              label: "二维码下发",
              type: "text",
              handle: async row => {
                console.log(22, row.deviceNo, row);
                let res = await this.apis.deviceSettingSetQRCode(row.deviceNo);
                this.$message({
                  type: res.code == 200 ? "success" : "error",
                  message: res.msg
                });
              }
            },
            {
              label: "使用记录",
              type: "text",
              isShow: () => {
                const role = sessionStorage.role;
                return role == "operator" || role == "agent" ? true : false;
              },
              handle: row => {
                this.$router.push({
                  path: "/device_management-Charging_record",
                  query: {
                    deviceNo: row.deviceNo
                  }
                });
              }
            },
            {
              label: "编辑",
              type: "text",
              handle: row => {
                this.add(row);
              }
            },
            {
              label: "删除",
              type: "text",
              handle: async row => {
                this.$confirm("确定要删除吗?", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning"
                })
                  .then(async () => {
                    var res = await this.apis.device_del({
                      id: row.id
                    });
                    this.$message({
                      type: "success",
                      message: "删除成功!"
                    });
                    this.init();
                  })
                  .catch(() => {});
              }
            }
          ]
        }
      ],
      tablePage: { limit: 10, page: 1, total: 0 },
      formData2: {
        deviceNo: "",
        deviceName: "",
        address: "",
        siteId: "",
        lng: "",
        lat: "",
        operatorId: "",
        agentId: "",
        cols: "",
        rows: "",
        sim: "",
        deviceType: "3",
        mealId: "",
        whetherPublic: null
      },
      formCols2: [
        {
          type: "input",
          label: "设备编号",
          placeholder: "请输入",
          width: 350,
          prop: "deviceNo"
        },
        {
          type: "input",
          label: "设备名称",
          placeholder: "请输入",
          width: 350,
          prop: "deviceName"
        },
        {
          type: "input",
          label: "列数",
          placeholder: "请输入",
          width: 350,
          prop: "cols",
          isDisabled: e => (e.id ? true : false)
        },
        {
          type: "input",
          label: "行数",
          placeholder: "请输入",
          width: 350,
          prop: "rows",
          isDisabled: e => (e.id ? true : false)
        },
        {
          type: "input",
          label: "sim 编号",
          placeholder: "请输入",
          width: 350,
          prop: "sim"
        },
        {
          type: "select",
          label: "设备类型",
          placeholder: "请输入",
          width: 350,
          prop: "whetherPublic",
          options: [
            { label: "内部设备", value: 0 },
            { label: "公开设备", value: 1 }
          ]
        },
        {
          type: "select",
          label: "选择运营商",
          placeholder: "请输入",
          width: 350,
          prop: "operatorId",
          options: [],
          isShow: () => {
            return sessionStorage.role == "platform" ? true : false;
          }
        },
        {
          type: "select",
          label: "选择代理商",
          placeholder: "请输入",
          width: 350,
          prop: "agentId",
          options: [],
          isShow: () => {
            return sessionStorage.role == "operator" ? true : false;
          }
        },
        {
          type: "select",
          label: "选择站点",
          placeholder: "请输入",
          width: 350,
          prop: "siteId",
          options: []
        },
        // {
        //   type: "select",
        //   label: "选择运维",
        //   placeholder: "请输入",
        //   width: 350,
        //   prop: "merId",
        //   options: [],
        //   isShow: () => {//operator是代理商
        //     return sessionStorage.role == "operator" ? true : false;
        //   },
        // },
        {
          type: "select",
          label: "关联套餐",
          placeholder: "请输入",
          width: 350,
          prop: "mealId",
          isShow: () => {
            return this.userType == "运营商" ? false : true;
          }
        },
        {
          type: "input",
          id: "suggestId",
          label: "站点地址",
          width: 350,
          prop: "address"
          // isShow: () => {
          //   return this.userType == "运营商" ? false : true;
          // }
        },
        {
          type: "slot",
          name: "slot3",
          label: "",
          prop: "lng"
          // isShow: () => {
          //   return this.userType == "运营商" ? false : true;
          // }
        }
      ],
      formRules2: {
        deviceNo: [{ required: true, message: "请输入", trigger: "blur" }],
        deviceName: [{ required: true, message: "请输入", trigger: "blur" }],
        cols: [
          { required: true, message: "请输入", trigger: "blur" },
          { validator: checkAge, trigger: "blur" }
        ],
        rows: [
          { required: true, message: "请输入", trigger: "blur" },
          { validator: checkAge, trigger: "blur" }
        ],
        sim: [{ required: true, message: "请输入", trigger: "blur" }],
        siteId: [{ required: true, message: "请选择站点", trigger: "blur" }],
        mealId: [{ required: true, message: "请输入套餐", trigger: "blur" }],
        operatorId: [
          { required: true, message: "请选择运营商", trigger: "blur" }
        ],
        agentId: [{ required: true, message: "请选择代理商", trigger: "blur" }],
        whetherPublic: [
          { required: true, message: "请选择类型", trigger: "blur" }
        ],
        // merId: [{ required: true, message: "请选择运维", trigger: "blur" }],
        lng: [
          { required: true, message: "请点击地图选择经纬度", trigger: "blur" }
        ],

        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" }
        ]
      },
      formHandle2: [
        {
          label: "取消",
          handle: e => this.elFormVisible("", "elForm2")
        },
        {
          label: "确定",
          type: "success",
          handle: e => this.elFormSubmit()
        }
      ],
      baiteng: { lat: "", lng: "" },
      tengbai: { lat: "", lng: "" }
    };
  },
  mounted() {
    console.log(sessionStorage.nickName);
    console.log(sessionStorage.optUserId);
    this.init();

    //userType为1是运营商，2是代理商
    if (sessionStorage.getItem("userType") == "1") {
      this.userType = "运营商";
    }
    if (sessionStorage.getItem("userType") == "2") {
      this.userType = "代理商";
    }

    if (sessionStorage.role == "platform") {
      this.operator_list();
    }
    if (sessionStorage.role == "operator") {
      this.agent_list();
      this.maintenancer_list();
      this.site_list();
    }
    if (sessionStorage.role !== "operator") {
      this.agent_list();
      this.site_listss();
    }

    this.mealExchange_list();
  },
  watch: {
    "formData2.agentId": {
      async handler(newVal, oldVal) {
        if (newVal) {
          this.site_listss(newVal);
        }
      },
      deep: true // 深度监听
    }
  },

  methods: {
    // 百度地图经纬度转为腾讯地图经纬度
    bdMapToTxMap(lat, lng) {
      console.log("百度地图经纬度", lat, lng);
      let pi = (3.14159265358979324 * 3000.0) / 180.0;
      let x = lng - 0.0065;
      let y = lat - 0.006;
      let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * pi);
      let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * pi);
      lng = z * Math.cos(theta);
      lat = z * Math.sin(theta);
      this.tengbai.lng = lng;
      this.tengbai.lat = lat;
      // console.log("百度 转 腾讯", lat, lng);
    },
    //  腾讯地图转百度地图经纬度
    txMapToBdMap(lat, lng) {
      let x_pi = (3.14159265358979324 * 3000.0) / 180.0;
      let x = lng;
      let y = lat;
      let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
      let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
      lng = z * Math.cos(theta) + 0.0065;
      lat = z * Math.sin(theta) + 0.006;
      this.baiteng.lng = lng;
      this.baiteng.lat = lat;
      // console.log("腾讯 转 百度", lat, lng);
    },
    async init() {
      let parm = {
        ...this.searchData,
        ...{
          pageNum: this.tablePage.page,
          pageSize: this.tablePage.limit
        }
      };
      let res = await this.apis.device_list(parm);
      if (res) {
        let key = "mealName";
        let keys = "name";
        this.tableData = res.rows;
        this.tablePage.total = res.total;
        this.tableData.forEach(item => {
          // 防止添加的属性值为空
          if (item.mealChargeEntity) {
            item[key] = item.mealChargeEntity.mealName;
          } else {
            item[key] = "-";
          }
          // 防止添加的属性值为空
          if (item.siteEntity) {
            item[keys] = item.siteEntity.name;
          } else {
            item[keys] = "-";
          }
        });
      }
    },
    // 编辑按钮出现后的编辑页面的  绑定确认按钮的方法
    async elFormSubmit() {
      this.bdMapToTxMap(this.formData2.lat, this.formData2.lng);
      this.formData2.lng = this.tengbai.lng;
      this.formData2.lat = this.tengbai.lat;
      this.$refs.elForm2.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if (this.formData2.id) {
            let res = await this.apis.device_updata(this.formData2);
            this.$message({
              type: res.code == 200 ? "success" : "error",
              message: res.msg
            });
            if (res) {
              this.init();
              this.elFormVisible("", "elForm2");
            }
          } else {
            let res = await this.apis.device_save(this.formData2);
            this.$message({
              type: res.code == 200 ? "success" : "error",
              message: res.msg
            });
            if (res) {
              this.init();
              this.elFormVisible("", "elForm2");
            }
          }
        }
      });
    },
    async changestate(row) {
      let res = await this.apis.device_updata({
        id: row.id,
        useStatus: row.useStatus
      });

      this.$message({
        message: "操作成功！",
        type: "success"
      });
    },
    elFormDetail(row) {
      Object.keys(this.formData).forEach(key => {
        this.formData[key] = row[key];
      });
      this.formData.status = row["state"] == 1 ? true : false;
      this.formData.id = row.id;
      this.elFormVisible();
    },

    map() {
      // 百度地图API功能
      function G(id) {
        return document.getElementById(id);
      }
      var that = this;
      var map = baidumap(that);
      this.baiduMap = map;
      var geoc = new BMap.Geocoder(); //地址解析对象
      var ssss = new BMap.Point(this.formData2.lng, this.formData2.lat); //获取经纬度
      var ac = new BMap.Autocomplete({ input: "suggestId", location: map }); // 建立一个自动完成的对象
      map.clearOverlays(); // 清除地图上所有覆盖物
      map.centerAndZoom(ssss, 20); //设置地图中心点
      map.addOverlay(new BMap.Marker(ssss)); // 添加标注
      // 点击地图某一个点  更新经纬度
      map.addEventListener("click", function(e) {
        that.formData2.lng = e.point.lng;
        that.formData2.lat = e.point.lat;
        var pt = e.point;
        map.clearOverlays(); // 清除地图上所有覆盖物
        map.addOverlay(new BMap.Marker(pt)); // 添加标注
        geoc.getLocation(pt, function(rs) {
          that.formData2.address = rs.address; //点击地图拿到详细地址
          // var addComp = rs.addressComponents;//点击地图拿到省 市 区 街
        });
      });
      // 选择下拉框的地址触发的事件
      var myValue;
      ac.addEventListener("onconfirm", function(e) {
        // 鼠标点击下拉列表后的事件
        var _value = e.item.value;
        myValue =
          _value.province +
          _value.city +
          _value.district +
          _value.street +
          _value.business;
        G("searchResultPanel").innerHTML =
          "onconfirm<br />index = " +
          e.item.index +
          "<br />myValue = " +
          myValue;

        // 通过传入地址，获取经纬度
        geoc.getPoint(myValue, function(point) {
          if (point) {
            that.formData2.lat = point.lat;
            that.formData2.lng = point.lng;
          }
        });
      });
      map.enableScrollWheelZoom(); //启用滚轮放大缩小，默认禁用
      map.enableContinuousZoom(); //启用地图惯性拖拽，默认禁用
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve();
        }, 10);
      });
    },
    add(row) {
      this.formData2.id = row.id;
      this.elFormVisible("", "elForm2").then(res => {
        this.txMapToBdMap(row.lat, row.lng);
        this.formData2.lng = this.baiteng.lng;
        this.formData2.lat = this.baiteng.lat;
        this.map().then(res => {
          Object.keys(this.formData2).forEach(key => {
            this.formData2[key] = row[key];
            this.formData2.lng = this.baiteng.lng;
            this.formData2.lat = this.baiteng.lat;
          });
        });
      });
    },
    //代理商下的  站点列表
    async site_listss(newVal) {
      const res = await this.apis.siteAgentList(newVal || "");
      const list = res.data || [];
      let options = [];
      list.map(res => {
        options.push({
          label: res.name,
          value: res.id
        });
      });
      this.formCols2[
        this.labIndex2(this.formCols2, "siteId")
      ].options = options;
      this.searchForm[
        this.labIndex2(this.searchForm, "siteId")
      ].options = options;
    },

    //运营商下的  站点列表
    async site_list() {
      const res = await this.apis.site_list({
        pageNum: 1,
        pageSize: 100000
      });
      const list = res.rows || [];
      let options = [];
      list.map(res => {
        options.push({
          label: res.name,
          value: res.id
        });
      });
      this.searchForm[
        this.labIndex2(this.searchForm, "siteId")
      ].options = options;
    },

    //运营商-列表
    async operator_list() {
      const res = await this.apis.operator_list({
        pageNum: 1,
        pageSize: 100000
      });
      const list = res.rows || [];
      let options = [];
      list.map(res => {
        options.push({
          label: res.name,
          value: res.id
        });
      });

      this.formCols2[
        this.labIndex2(this.formCols2, "operatorId")
      ].options = options;
      this.searchForm[
        this.labIndex2(this.searchForm, "operatorId")
      ].options = options;
    },

    //代理商列表
    async agent_list() {
      const res = await this.apis.agent_list({
        pageNum: 1,
        pageSize: 100000
      });
      if (sessionStorage.role !== "operator" && res.rows.length == 0) {
        var list = [
          {
            name: sessionStorage.nickName,
            id: sessionStorage.optUserId
          }
        ];
      } else {
        var list = res.rows || [];
      }
      let options = [];
      list.map(res => {
        options.push({
          label: res.name,
          value: res.id
        });
      });
      this.searchForm[
        this.labIndex2(this.searchForm, "agentId")
      ].options = options;
      this.formCols2[
        this.labIndex2(this.formCols2, "agentId")
      ].options = options;
    },
    //运维员列表
    async maintenancer_list() {
      const res = await this.apis.maintenancer_list({
        pageNum: 1,
        pageSize: 1000000
      });
      const list = res.rows || [];
      let options = [];
      list.map(res => {
        options.push({
          label: res.userName,
          value: res.id
        });
      });

      // this.formCols2[this.labIndex2(this.formCols2, "merId")].options = options;
    },

    //套餐列表
    async mealExchange_list() {
      const res = await this.apis.mealCharge_list({
        pageNum: 1,
        pageSize: 1000
      });
      const list = res.rows || [];
      let options = [];
      list.map(res => {
        options.push({
          label: res.mealName,
          value: res.id
        });
      });
      this.formCols2[
        this.labIndex2(this.formCols2, "mealId")
      ].options = options;
    },

    warehouse_gate_dall() {
      this.warehouse_gate_data.show = false;
    },

    formatSeconds(value) {
      var theTime1 = parseInt(value); // 需要转换的时间分钟
      var theTime2 = 0; // 小时
      var theTime3 = 0; // 天

      if (theTime1 > 60) {
        theTime2 = parseInt(theTime1 / 60);
        theTime1 = parseInt(theTime1 % 60);
        if (theTime2 > 24) {
          // 大于24小时
          theTime3 = parseInt(theTime2 / 24);
          theTime2 = parseInt(theTime2 % 24);
        }
      }
      var result = "";
      if (theTime1 > 0) {
        result = "" + parseInt(theTime1) + "分钟";
      }
      if (theTime2 > 0) {
        result = "" + parseInt(theTime2) + "小时" + result;
      }
      if (theTime3 > 0) {
        result = "" + parseInt(theTime3) + "天" + result;
      }
      return result;
    }
  }
};
</script>
<style scoped lang="scss">
.el-icon-search {
  margin-right: 10px;
}

#l-map {
  height: 250px;
  width: 100%;
}
</style>
